# encoding: utf-8
from message.api import MessageService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 用户名和授权码
sender = "smilechris@yeah.net"
userAuth = ""


class MessageServiceImpl:

    def sendMobileMessage(self, mobile, message):
        print("send mobile message")
        return True

    def sendEmailMessage(self, email, message):
        messageObj = MIMEText(message, 'plain', "utf-8")
        # messageObj["from"] = "chirs test"
        messageObj["to"] = email
        messageObj["subject"] = Header("test information", "utf-8")
        try:
            smtpObj = smtplib.SMTP("smtp.yeah.net")
            smtpObj.login(sender, userAuth)
            smtpObj.sendmail(sender, [email], messageObj.as_string())
            print("send email success")
            return True
        except smtplib.SMTPException as ex:
            print("send email fail:", ex)
            return False


if __name__ == "__main__":
    handle = MessageServiceImpl()
    processer = MessageService.Processor(handle)
    scoket = TSocket.TServerSocket("127.0.0.1", 9090)
    transport = TTransport.TFramedTransportFactory()
    protocol = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processer, scoket, transport, protocol)
    print("thrift server start...")
    server.serve()
    print("thrift server exit...")
